import { HomePageMediaCoverageItem, HomePageMediaCoverageRes } from '@/api/home';
import { CoverNumberItemModel } from '@/views/home/home.module';
// import type { IMini } from '@/shims-vue';

export function isIos(): boolean {
    return !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
}

export function toFixedTwo(num: number) {
    // 使用toFixed()方法来控制小数位数，确保小数位数是两位
    return parseFloat(num.toString()).toFixed(2);
}

// 将阿拉伯数字转化为中文
export function convertToChineseNumeral(number: number | string): string {
    const num = Number(number);
    if (num === 10) {
        return '十';
    } else if (num === 1) {
        return '一';
    }
    const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    const units = ['', '十', '百', '千', '万'];
    let result = '';
    const numStr = num.toString();
    for (let i = 0; i < numStr.length; i++) {
        const digit = parseInt(numStr.charAt(i), 10);
        const unit = units[numStr.length - i - 1];
        if (digit === 0) {
            // 当前数字为0时不需要输出汉字，但需要考虑上一个数字是否为0，避免出现连续的零
            if (result.charAt(result.length - 1) !== '零') {
                result += '零';
            }
        } else {
            result += digits[digit] + unit;
        }
    }
    // 对于一些特殊的数字，如10、100等，需要在最前面加上“一”
    if (result.charAt(0) === '一') {
        result = result.substr(1, result.length);
    } else if (result.charAt(0) === '百') {
        result = '一' + result;
    } else if (result.charAt(0) === '千') {
        result = '一' + result;
    }
    return result.toString();
}

// 获取最近的周六日期
export function getNextSatDate(): Date {
    const timeDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
    const dateObj = new Date();
    let satDistance = 6 - dateObj.getDay(); // 还差几天到周六
    satDistance = satDistance === 0 ? 7 : satDistance; // 当天是周六调到下周六
    return new Date(dateObj.getTime() + satDistance * timeDay); // 最近的周六
}

export const getImageUrl = (name: string) => {
    return new URL(
        // 本地资源路径
        `/src/assets/img/${name}`,
        import.meta.url
    ).href;
};

// http替换成https
export function getPdfArrayBufferNew(url: string): string {
    const protocol = window.location.protocol;
    if (protocol === 'https:' && url.indexOf(protocol) === -1) {
        return url.replace('http:', 'https:');
    }
    return url;
}

export function downLoadCommon(url: string, { allNew, name } = { allNew: true, name: '' }) {
    const a = document.createElement('a');
    const event = new MouseEvent('click');
    console.log(url);
    a.download = name || url.substring(url.lastIndexOf('/') + 1).toLowerCase();
    const httpsUrl = getPdfArrayBufferNew(url);
    a.href = httpsUrl;
    const imgTypes = ['pdf', 'jpg', 'jpeg', 'png', 'img', 'txt', 'gif', 'bmp', 'psd', 'raw', 'tif', 'tiff'];
    const type = httpsUrl.substring(httpsUrl.lastIndexOf('.') + 1).toLowerCase();
    if (allNew) {
        a.target = '_blank';
    } else if (imgTypes.includes(type)) {
        a.target = '_blank';
    }
    a.dispatchEvent(event);
}
// 日期转化为星期几
export function getWeek(time: string | Date): string {
    const datas = new Date(time).getDay();
    const week = ['日', '一', '二', '三', '四', '五', '六'];
    return '星期' + week[datas];
}

// 处理媒体资源数据为指定数组
export const handleMediaResource = (data: HomePageMediaCoverageRes) => {
    let tableData: CoverNumberItemModel[] = [];
    const screenData: HomePageMediaCoverageItem = data.mediaResourceSummaryList?.find((item: HomePageMediaCoverageItem) => item.mediaType === 1) || {};
    const lcdData: HomePageMediaCoverageItem = data.mediaResourceSummaryList?.find((item: HomePageMediaCoverageItem) => item.mediaType === 2) || {};
    const posterData: HomePageMediaCoverageItem = data.mediaResourceSummaryList?.find((item: HomePageMediaCoverageItem) => item.mediaType === 3) || {};

    tableData = [{
        type: 1,
        name: '楼盘数',
        total: data.resourceSummary.premisesNum || 0,
        screen: screenData.premisesNum || 0,
        lcd: lcdData.premisesNum || 0,
        poster: posterData.premisesNum || 0,
    },
    {
        type: 2,
        name: '电梯数',
        total: data.resourceSummary.elevatorsNum || 0,
        screen: screenData.elevatorsNum || 0,
        lcd: lcdData.elevatorsNum || 0,
        poster: posterData.elevatorsNum || 0,
    }, {
        type: 3,
        name: '点位数',
        total: data.resourceSummary.pointNum || 0,
        screen: screenData.pointNum || 0,
        lcd: lcdData.pointNum || 0,
        poster: posterData.pointNum || 0,
    }, {
        type: 4,
        name: '覆盖人数',
        total: data.resourceSummary.coveredPeopleNum || 0,
        screen: screenData.coveredPeopleNum || 0,
        lcd: lcdData.coveredPeopleNum || 0,
        poster: posterData.coveredPeopleNum || 0,
    },{
        type: 5,
        name: '覆盖家庭',
        total: data.resourceSummary.coveredHouseholdNum || 0,
        screen: screenData.coveredHouseholdNum || 0,
        lcd: lcdData.coveredHouseholdNum || 0,
        poster: posterData.coveredHouseholdNum || 0,
    }];

    return tableData;
};


export const handleRatio = (num: number, unit = '', fixed = 0): number | string => {
    return (num * 100).toFixed(fixed) + unit;
};


export const isWx = () => {
    return new Promise(resolve => {
        try {
            if (window.__wxjs_environment === 'miniprogram') {
                resolve('mini-wx');
            } else {
                resolve('no-mini-wx');
            }
            // window.wx?.miniProgram.getEnv((res: IMini) => {
            //     if (res.miniprogram) {
            //         resolve('mini-wx');
            //     } else {
            //         resolve('no-mini-wx');
            //     }
            // });
        } catch (err) {
            resolve('no-mini-wx');
            console.log(err);
        }
    });
};


export const copyText = (text: string, cb?: () => unknown) => {
    const textarea = document.createElement('textarea'); // 创建一个 textarea 元素
    textarea.setAttribute('readonly', 'true');
    textarea.value = text; // 将要复制的文本赋值给 textarea 的 value 属性
    document.body.appendChild(textarea); // 将 textarea 元素添加到页面中
    textarea.select(); // 选中 textarea 的内容
    document.execCommand('SelectAll');
    document.execCommand('copy'); // 执行复制命令
    document.body.removeChild(textarea); // 移除 textarea 元素
    cb && cb();
};


export const downloadFile = (url: string) => {
    if(!url){
        return false;
    }

    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    const strs=url.split('/');
    xhr.onload = function () {
        if (this.status === 200) {
            const blob = new Blob([this.response]);
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = strs[strs.length-1];// "myfile.pdf";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    };
    xhr.send();
};
